#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/8/6 21:07
class MementoCaretaker:
    """
    导航备忘录管理类
    """
    def __init__(self, size=20):
        self.previous_list = list()
        self.current = None
        self.after_list = list()
        self.size = size

    def add(self, data):
        if data is None:
            return
        if self.current is None:
            self.current = data
        elif self.current.relative_path == data.relative_path:
            return
        elif self.previous_list is not None and len(self.previous_list) > 0 and self.previous_list[-1].relative_path == data.relative_path:
            self.backward()
        elif self.after_list is not None and len(self.after_list) > 0 and self.after_list[0].relative_path == data.relative_path:
            self.forward()
        else:
            self.previous_list.append(self.current)
            self.current = data

    def backward(self, i:int=-1):
        if self.previous_list is None or len(self.previous_list) == 0:
            return None
        size = len(self.previous_list)
        if i < -size or i >= size:
            return None
        if self.after_list is None:
            self.after_list = []
        if self.current is not None:
            self.after_list = [self.current] + self.after_list
        self.current = self.previous_list[i]
        i = i if i >= 0 else len(self.previous_list) - abs(i) # 如果索引为负向索引，则转换成正向索引
        temp_list = self.previous_list[i + 1:]
        self.after_list = temp_list + self.after_list
        self.previous_list = self.previous_list[0:i]
        # 删除溢出元素
        if self.previous_list is not None and len(self.previous_list) == self.size:
            self.previous_list = self.previous_list[-self.size:]
        if self.after_list is not None and len(self.after_list) == self.size:
            self.after_list = self.after_list[0:self.size]

    def forward(self, i:int=0):
        if self.after_list is None or len(self.after_list) == 0:
            return None
        size = len(self.after_list)
        if i < -size or i >= size:
            return None
        if self.previous_list is None:
            self.previous_list = []
        if self.current is not None:
            self.previous_list.append(self.current)
        self.current = self.after_list[i]
        i = i if i >= 0 else len(self.previous_list) - abs(i)  # 如果索引为负向索引，则转换成正向索引
        temp_list = self.after_list[0:i]
        self.previous_list.extend(temp_list)
        self.after_list = self.after_list[i+1:]
        # 删除溢出元素
        if self.previous_list is not None and len(self.previous_list) == self.size:
            self.previous_list = self.previous_list[-self.size:]
        if self.after_list is not None and len(self.after_list) == self.size:
            self.after_list = self.after_list[0:self.size]


